/**
 * 表单设计器----参照（old）
 */
mini.parse();
var refId;
var menuId;
var tree = mini.get('tree1');
var menusFormTypes;

 var grid1 = mini.get("gridField");
 var grid = mini.get("noTreeGrid");
 var searchColsEl = mini.get("searchCols");				//筛选下拉元素
 var searchKeyEl = mini.get("searchKey");				//筛选输入框
var formSh = localStorage.getItem("formShow");
console.log(formSh);
var formSh1=$.parseJSON(formSh);
console.log(formSh1);

var columnsArr = [];			//存放列(用作查询下拉字段)
// $.ajax({
//     url: ajaxUrl + "/tableClass/list.do",
//     type: "post",
//     dataType: "json",
//     data : {
//     },
//     success: function(data) {
//         console.log(data);
//         var mainTreeData = dbTree(grid,data.data);//获取主表树
//     },
//     error : function(data){
//         alert('获取失败');
//     }
// });
 var treeSize = mini.get('treeSize');

function init() {
	// refId(formListId) 查找表单类型


	//数据
	$.ajax({
		url: ajaxUrl + "/formltems/findFormSource.do",
		type: "post",
		dataType: "json",
		traditional: true,
		data: {
			formListId: refId,
			menuId: menuId
		},
		success: function (data) {
			menusFormTypes = data[0].formList.formTypes;	//类型（列表档案/）
			// grid_data = data;
			// grid = new mini.DataGrid();//js创建表格
			// console.log(grid, '动态创建的表格');
			// grid.set({
			// 	url: "",
			// 	style: "width:100%;height:300px;",
			// 	id: "datagrid",
			// 	columns: cols,
			// 	multiSelect: false,
			// 	allowResize: false,
			// 	allowCellEdit: false,
			// 	allowCellSelect: true,
			// 	cellEditAction: "cellclick",
			// 	allowRowSelect: true,
			// 	showPager: false,
			// 	editNextOnEnterKey: true,
			// 	editNextRowCell: true
			// });
			//
			// grid.render(document.getElementById('noTreeGrid'));
			// // var data = [{loginname:"222",id:1},{}];
			// grid.setData(grid_data);
;
			console.log(typeof menusFormTypes)
			if(menusFormTypes == 'file' || menusFormTypes == 'form'){
				console.log(menuId);
				//没有树
				//treeSize.
				$('#treeSize').css('display','none');
				//加载列
				//onCol('noTreeGrid');
				//加载列

				$.ajax({
					url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
					type: "post",
					dataType: "json",
					traditional: true,
					data: {
						formListId: refId,
						menuId: menuId
					},
					success: function(data){
						for(var i=0;i<data.length;i++) {
							if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab') {
								cTableName = data[i].tableName;//获得主表名
							}
						}
						cols = data;

						//处理列数据为下拉框数据
						var columnsData = data;
						//如果第一个是选择框，那么删除选择框
						if(columnsData[0].type == "checkcolumn"){
							columnsData.shift();
						}
						console.log(columnsData,'删除选择框以后的数组')
						columnsData.forEach(function (item) {
							var colObj = {};
							colObj.id = item.field;
							colObj.text = item.header;
							columnsArr.push(colObj);
						});
						console.log(columnsArr,'列数据');
						searchColsEl.setData(columnsArr);
						//数据
						$.ajax({
							url: ajaxUrl + "/sqlAction/findAll.do",
							type: "post",
							dataType: "json",
							traditional: true,
							data: {
								formListId: refId,
							},
							success: function(data) {
								grid_data = data;
								console.log(grid_data, '数据');
								grid1 = new mini.DataGrid();//js创建表格
								grid1.set({
									url: "",
									style: "width:100%;height:300px;",
									id: "datagrid",
									columns: cols,
									multiSelect: false,
									allowResize: false,
									allowCellEdit: false,
									allowCellSelect: true,
									cellEditAction: "cellclick",
									allowRowSelect: true,
									showPager: false,
									editNextOnEnterKey: true,
									editNextRowCell: true
								});

								grid1.render(document.getElementById('noTreeGrid'));
								//grid1.load();
								//var data = [{loginname:"222",id:1},{}];
								console.log(grid1, 'grid1');
								grid1.setData(grid_data);
							},
							error : function(data){
								mini.alert('获取失败')
							}
						});
					},
					error : function(data){
						mini.alert('获取失败')
					}
				});
			}else{
				$('#noTreeGrid').css('display','none');
				$('#treeSize').css('display','block');
				//加载树
				$.ajax({
					url: ajaxUrl + "/formltems/formTree.do",
					type: "POST",
					dataType: "json",
					data: {
						formListId: refId,
					},
					success: function(data){
						var treeData = data[0];
						console.log(treeData);
						tree.setData(data);
						//tree.loadData(data);
					}
				});
				//加载表
				$.ajax({
					url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
					type: "post",
					dataType: "json",
					traditional: true,
					data: {
						formListId: refId,
						menuId: menuId
					},
					success: function(data){
						for(var i=0;i<data.length;i++) {
							if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab') {
								cTableName = data[i].tableName;//获得主表名
							}
						}
						cols = data;
						//处理列数据为下拉框数据
						var columnsData = data;
						//如果第一个是选择框，那么删除选择框
						if(columnsData[0].type == "checkcolumn"){
							columnsData.shift();
						}
						console.log(columnsData,'删除选择框以后的数组')
						columnsData.forEach(function (item) {
							var colObj = {};
							colObj.id = item.field;
							colObj.text = item.header;
							columnsArr.push(colObj);
						});
						console.log(columnsArr,'列数据');
						searchColsEl.setData(columnsArr);
						//数据
						$.ajax({
							url: ajaxUrl + "/sqlAction/findAll.do",
							type: "post",
							dataType: "json",
							traditional: true,
							data: {
								formListId: refId,
							},
							success: function(data){
								grid_data = data;
								console.log(grid_data,'数据');
								grid1 = new mini.DataGrid();//js创建表格
								grid1.set({
									url: "",
									style:"width:100%;height:300px;",
									id:"datagrid",
									columns: cols,
									multiSelect:false,
									allowResize:false,
									allowCellEdit:false,
									allowCellSelect:true,
									cellEditAction: "cellclick",
									allowRowSelect: true,
									showPager:false,
									editNextOnEnterKey:true,
									editNextRowCell:true
								});

								grid1.render(document.getElementById('gridField'));
								//grid1.load();
								// var data = [{loginname:"222",id:1},{}];
								console.log(grid1,'grid1');
								grid1.setData(grid_data);
							},
							error : function(data){
								mini.alert('获取失败')
							}
						});
					},
					error : function(data){
						mini.alert('获取失败')
					}
				});
			}



		},
		error : function(data){
		}
	})



}
//列
function onCol(grid1){
    //加载列
    $.ajax({
        url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
        type: "post",
        dataType: "json",
        traditional: true,
        data: {
            formListId: refId,
            menuId: menuId
        },
        success: function(data){
            for(var i=0;i<data.length;i++) {
                if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab') {
                    cTableName = data[i].tableName;//获得主表名
                }
            }
            cols = data;
            //数据
            $.ajax({
                url: ajaxUrl + "/sqlAction/findAll.do",
                type: "post",
                dataType: "json",
                traditional: true,
                data: {
                    formListId: refId,
                },
                success: function(data){
                    grid_data = data;
                    grid1 = new mini.DataGrid();//js创建表格
                    console.log(grid1,'动态创建的表格');
                    grid1.set({
                        url: "",
                        style:"width:100%;height:300px;",
                        id:"datagrid",
                        columns: cols,
                        multiSelect:false,
                        allowResize:false,
                        allowCellEdit:false,
                        allowCellSelect:true,
                        cellEditAction: "cellclick",
                        allowRowSelect: true,
                        showPager:false,
                        editNextOnEnterKey:true,
                        editNextRowCell:true
                    });
                    
                    grid1.render(document.getElementById('grid1'));
                    //grid1.load();
                    // var data = [{loginname:"222",id:1},{}];
                    grid1.setData(grid_data);
                },
                error : function(data){
                    mini.alert('获取失败')
                }
            });
        },
        error : function(data){
            mini.alert('获取失败')
        }
    });
}
var clickNodeFlag = 0;
//点击树节点
 tree.on("nodeselect", function (e) {
	 console.log(e);
     clickNodeFlag++;
     treeSelected = e.selected;
     nodes = tree.getAncestors(treeSelected);
     nodes.push(treeSelected);
     console.log("e.node.tabName:" + e.node.tabName);
     $.ajax({
         url: ajaxUrl + "/formltems/selectArchives.do",
         //url:"http://192.168.31.65:8080/bpm/formltems/selectArchives.do",
         type: "post",
         dataType: "json",
         data: {
             formListId: refId,
             condition: e.node.tabName,
             conValue: e.node.id
         },
         success: function(data){
        	 console.log(data,'点击节点获取值');
             grid_data = data.data;
             grid1.setData(grid_data);
         },
         error : function(data){
         }
     });                    
})
function SetData(data) {
	console.log(data);
    var data = mini.clone(data);
//    refId = data.ref.id.replace(/[^0-9]/ig,"")+'';
    refId = data.ref.formListId;
    menuId = data.menuId;
    // menusFormTypes = data.menusFormTypes;	//类型（列表档案/）
    init();
}

//确定按钮之前
function onTableOk() {
    var grid = mini.get("datagrid");
    var gridSelected = grid.getSelected();
    if(gridSelected) {
        return gridSelected; //返回选中的数据给父组件
    }else {
        mini.alert('请选择字段！');
        return;
    }
}

//确定按钮
function onOk(e) {
    CloseWindow("ok");
}
//取消按钮
function onCancel(e) {
    CloseWindow("cancel");
}

function CloseWindow(action) {

    if (window.CloseOwnerWindow)
        return window.CloseOwnerWindow(action);
    else
        window.close();
}

//表格树数据加载
var dbData = [];//存放转换后的数据库表数据
function dbTree(grid,data) {
    for(var i=0;i<data.length;i++) {
        dbData[i] = {
            tableClassName: data[i].tableClassName,
            tableChClassName: data[i].tableChClassName,
            cTableName: data[i].tableChClassName,
            field: '',
            fieldCh: '',
            tableClassId: data[i].tableClassId + '',//id
            PID: -1,
            checked: false,
            expanded: true,
            children:[]
        };
        for(var j=0;j<data[i].createTables.length;j++) {
            var c = data[i].createTables[j];
            dbData[i].children.push({
                // cTableField: c.field,
                cTableName: data[i].tableChClassName,
                tableClassName: data[i].tableClassName,
                // formListId: data[i].formListId,
                type: c.type,
                field: c.field,
                fieldCh: c.fieldCh,
                tableClassId: c.tableId + '',//id
                PID: data[i].tableClassId + '',
                expanded: true,
                checked: false
            });
        }
    }
    grid.setData(dbData);
    return dbData;
}
//查询
function search() {
	var colVal = searchColsEl.getValue();
	var keyVal = searchKeyEl.getValue();
	if(colVal){
		if(keyVal){
			var searchObj = {
				colVal: colVal,
				keyVal: keyVal,
				cTableName: formSh1.cTableName,
				formListId: formSh1.formListId
			};
			var jsonStr = JSON.stringify(searchObj);
			$.ajax({
				url: ajaxUrl + '/sqlAction/findFilter.do',
				type: 'POST',
				data: jsonStr,
				contentType : "application/json",
				success: function (data) {
					console.log(data);
					//无树
					if(menusFormTypes == 'file'){
						grid1.setData(data);
					//有树
					}else{
						grid1.setData(data);
					}
				},
				error: function (data) {
					mini.alert('请求失败')
				}
			})
		}else{
			mini.alert('请选择需要搜索的项');
		}
	}else{
		mini.alert('请选择需要查询的列')
	}
}